package thread;

public class SyncDemo {
    public static boolean p1 = false;
    public static boolean p2 = false;
    public static void main(String[] args) {
        Bank bank = new Bank();
        int flag = 0;
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++){
            Thread t1 = new Thread() {
                public void run() {
                    p1 = bank.getMoney(20000);

                }
            };
            Thread t2 = new Thread() {
                public void run() {
                    p2 = bank.getMoney(20000);
            }
        };

            t1.start();
            t2.start();
            try {
                Thread.sleep(20);
            } catch (Exception e) {
            }
        if (p1 & p2) {
            flag++;
            bank.saveAccount(20000);
        }else {

            p1 = false;
            p2 = false;
            bank.saveAccount(20000);
        }
    }
        long end = System.currentTimeMillis();
        System.out.println(flag+"个成功，耗时："+(end-start)+"ms");

    }
}
class Bank {
    private int account = 20000;
    public synchronized boolean getMoney(int money){
        int account = getAccount();
        if(money<=account){
            account -= money;
            Thread.yield();
            saveAccount(account);
            return true;
        }
        return false;
    }
    public void saveAccount(int account){
        this.account = account;
    }
    private int getAccount(){
        return account;
    }
}


















